import { getToken } from '@/utils/auth'

// 登录页面
const loginPage = "/pages/login"
  
// 页面白名单
const whiteList = [
  '/pages/login', '/pages/common/webview/index','/pages/common/article/index'
]

// 检查地址白名单
function checkWhite(url) {
  const path = url.split('?')[0]
  return whiteList.indexOf(path) !== -1
}
export function checkLogin(hash){
	let url = hash.substring(1, hash.indexOf('?'))
	console.info(url)
	if (getToken()) {
	  if (url === loginPage) {
	    uni.reLaunch({ url: "/" })
	  }
	  return true
	} else {
	  if (checkWhite(url)) {
	    return true
	  }
	  uni.reLaunch({ url: loginPage })
	  return false
	}
}

// 页面跳转验证拦截器
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]
list.forEach(item => {
  uni.addInterceptor(item, {
    invoke(to) {
      if (getToken()) {
        if (to.url === loginPage) {
          uni.reLaunch({ url: "/" })
        }
        return true
      } else {
        if (checkWhite(to.url)) {
          return true
        }
        uni.reLaunch({ url: loginPage })
        return false
      }
    },
    fail(err) {
      console.log(err)
    }
  })
})

uni.addInterceptor('request', {
  invoke(args) {
    // request 触发前拼接 url 
    console.log(args.url)
  },
  success(args) {
    // 请求成功后，修改code值为1
    //args.data.code = 1
  }, 
  fail(err) {
    console.log('interceptor-fail',err)
  }, 
  complete(res) {
    console.log('interceptor-complete',res)
  }
})